<template>
  <div>
    <div>
      <div v-if="!readonly && mode == 'small'" class="small-mode-add">
        <div ref="uploadcontainer" style="display: inline-block;">
          <div class="btn" ref="upload">
            <i-button type="primary" :disabled="value.length >= max"
              >上传 {{ value.length + "/" + max }}</i-button
            >
          </div>
        </div>
        <span>{{ description }}</span>
        <Tooltip placement="top-end">
          <Icon type="ios-help-outline" size="16" style="vertical-align: text-bottom;"></Icon>
          <div slot="content">
            <p>支持的文件格式：</p>
            <p style="word-break: break-all;word-wrap:break-word;white-space: normal;">
              {{ extensions }}
            </p>
          </div>
        </Tooltip>
      </div>
      <div
        v-if="!showSpecialImgType && showPreview"
        v-for="(item, index) in value"
        :key="index"
        class="ivu-uploaded"
      >
        <span v-show="item.isDefault" class="viewer-corner">
          <Icon type="md-checkmark" />
        </span>
        <div class="opt-panel">
          <div class="viewer" v-if="!readonly">
            <div v-show="!item.isDefault" class="viewer-select-btn" @click="select(item, index)">
              选择
            </div>
            <div v-show="item.isDefault" class="viewer-select-btn viewer-selected-btn">已选择</div>
          </div>
          <div class="viewer" v-if="isImage(item.url)">
            <div class="viewer-preview-btn" @click="delFile(item, index, true)">
              <Icon type="md-trash" />
            </div>
          </div>
          <div class="viewer" @click="showBig(index, false)" v-if="isImage(item.url)">
            <img class="enlarge-icon" width="16" alt src="@/assets/img/enlarge.png" />
          </div>
        </div>

        <img :src="item.url" alt v-if="isImage(item.url)" class="image-normal" />
        <img
          class="file-img2"
          src="https://feres.cpdaily.com/cpdaily/images/pdf.png"
          alt
          v-if="fileExtCheck(item.url, 'pdf')"
        />
        <img
          class="file-img2"
          src="https://feres.cpdaily.com/cpdaily/images/zip.png"
          alt
          v-if="fileExtCheck(item.url, 'zip')"
        />
        <img
          class="file-img2"
          src="https://feres.cpdaily.com/cpdaily/images/ppt.png"
          alt
          v-if="fileExtCheck(item.url, 'ppt') || fileExtCheck(item.url, 'pptx')"
        />
        <img
          class="file-img2"
          src="https://feres.cpdaily.com/cpdaily/images/doc.png"
          alt
          v-if="fileExtCheck(item.url, 'doc') || fileExtCheck(item.url, 'docx')"
        />
        <img
          class="file-img2"
          src="https://feres.cpdaily.com/cpdaily/images/xlsx.png"
          alt
          v-if="fileExtCheck(item.url, 'xlsx') || fileExtCheck(item.url, 'xls')"
        />
        <img
          v-if="false"
          class="file-img"
          src=""
          alt
        />
      </div>

      <div
        v-if="showSpecialImgType && showPreview"
        v-for="(item, index) in value"
        :key="index"
        class="ivu-uploaded"
      >
        <div class="opt-panel">
          <div class="viewer" @click="delFile(item, index, false)">
            <Icon type="md-trash" size="24" />
            <div>删除</div>
          </div>
          <div class="viewer" @click="showBig(index, true)" v-if="isImage(item.url)">
            <Icon type="md-eye" size="24" />
            <div>预览图片</div>
          </div>
        </div>
        <img :src="item.url" alt v-if="isImage(item.url)" class="image-normal" />
      </div>
      <div
        v-show="isExceedFive"
        class="ivu-upload ivu-upload-drag"
        ref="uploadcontainer"
        v-if="!readonly && mode == 'big'"
        @click="upload($event)"
      >
        <div ref="upload">
          <input type="file" class="ivu-upload-input" multiple />
          <Icon type="plus-circled" size="39" color="#2d8cf0" v-if="!uploading"></Icon>
          <img
            v-else
            src=""
            alt
          />
          <Icon v-if="!uploading" :type="iconType" size="32" />
          <p class="text">{{ title }}</p>
          <!-- <div>{{value.length+'/'+max}}</div> -->
          <div>{{ description }}</div>
        </div>
      </div>
      <div v-if="readonly && value.length == 0" class="empty">{{ emptyText }}</div>
    </div>
    <image-viewer
      :source="urlList"
      :thumbnail-show="false"
      ref="imageViewer"
      :className="className"
    ></image-viewer>
  </div>
</template>
<script type="application/ecmascript">
/**
   *
   * @example
   *
   <file-upload
   :value.sync="options.model.attachZip"
   title="上传附件"
   :max="3"
   description="仅支持20M以内的zip、pdf文件"
   max-file-size="20mb"
   extensions="zip,pdf"
   policy-url="/wec-msg-mngt/msgmngt/getImportPolicy"
   oss-file-url="/wec-msg-mngt/msgmngt/previewAttachment"
   :oss-file-url-setting="{filePathKey:'ossKey'}"
   :readonly="options.viewMode == 'view'"
   :params="{fileType:2}"
   empty-text="没有附件"
   @file-uploaded="fileUploaded2" @on-del="fileDel2" style="width: 900px;">
   </file-upload>
   *
   *
   * @event
   *
   * file-uploaded  文件上传完成事件 参数：({fileName, filePath, ext})
   * on-del 删除文件事件 参数 ({fileName, url...})
   *
   */
import upload from "./upload.js";
import imageViewer from "./imageViewer.vue";
import _ from "lodash";
import axios from "@/utils/ajax";

var ossFileUrlSettingDefault = {
  filePathKey: "filePath",
  fullPathKey: "datas"
};

var overMaxTip = null;

export default {
  components: { imageViewer },
  props: {
    className: {
      type: String,
      default: ""
    },
    /**
     * 是否显示预览
     */
    showPreview: {
      type: Boolean,
      default: true
    },
    /**
     * 是否只读
     *
     */
    readonly: {
      type: Boolean,
      default: false
    },

    mode: {
      type: String,
      default: "big"
    },

    /**
     * policyUrl接口传的参数
     */
    params: {
      type: Object
    },

    /**
     * 上传文件列表
     *
     * 例如：[{title:'', url:'http://kdlsfjslfjk'}]
     */
    value: {
      type: Array,
      default: function() {
        return [];
      }
    },

    /**
     * 上传文件个数限制
     */
    max: {
      type: Number,
      default: 2
    },

    showSpecialImgType: {
      type: Boolean,
      default: false
    },

    /**
     * 上传文件大小限制
     *
     * 例如：10mb
     */
    maxFileSize: {
      type: String,
      default: ""
    },

    /**
     * 上传按钮标题
     *
     * 例如：上传照片
     */
    title: {
      type: String,
      default: ""
    },

    /**
     * 上传按钮描述文字
     *
     * 例如：仅支持3.0M以内的JPEG、PNG文件
     */
    description: {
      type: String,
      default: ""
    },
    iconType: {
      type: String,
      default: ""
    },

    /**
     * 只读模式时 没有数据的提示消息
     */
    emptyText: {
      type: String,
      default: "咱无数据"
    },

    /**
     * 允许上传文件的格式
     *
     * 例如：jpg,png,jpeg,html,zip
     */
    extensions: {
      type: String,
      default: ""
    },

    /**
     * 获取上传policy的接口
     * 接口返回实例
     *  {
     *    "datas":{
     *      "accessid":"LTAI7iYVGqI46iFV",
     *      "dir":"examinee/1018650047507463/attachimage/28",
     *      "host":"http://ir-cr-file-test.oss-cn-hangzhou.aliyuncs.com",
     *      "policy":"eyJleHBpcmF0aW9uIjoiMjAxNy0xMC0xMVQxMDo0MDozMi4yODFaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCJleGFtaW5lZS8xMDE4NjUwMDQ3NTA3NDYzL2F0dGFjaGltYWdlLzI4Il1dfQ==",
     *      "signature":"kooIJ5hCf3Jm/ackzykKkbS7lvQ=","fileName":"examinee/1018650047507463/attachimage/28/28_5e0adbe9410f4efebf3face066770f18"
     *    },
     *    "code":"0",
     *    "message":null
     *   }
     */
    policyUrl: {
      type: String,
      default: ""
    },

    /**
     * 获取上传到oss后的文件可访问路径接口
     *
     * 接口传参：filePath: "examinee/1018650047507463/attachimage/28/28_5e0adbe9410f4efebf3face066770f18.jpeg"
     *
     * 接口返回：
     *  {
     *    "datas":"http://ir-cr-file-test.oss-cn-hangzhou.aliyuncs.com/examinee/1018650047507463/attachimage/28/28_5e0adbe9410f4efebf3face066770f18.jpeg?Expires=1823078392&OSSAccessKeyId=LTAI7iYVGqI46iFV&Signature=ruAlJ3sG9wzUxlcgY0nqKvX6sbc%3D",
     *    "code":"0",
     *    "message":null
     *  }
     */
    ossFileUrl: {
      type: String,
      default: ""
    },

    downloadFileUrl: {
      type: String,
      default: ""
    },

    /**
     * ossFileUrl接口key值配置
     * {
     *    'filePathKey':'filePath',
     *    'fullPathKey':'datas'
     * }
     *
     */
    ossFileUrlSetting: {
      type: Object
    }
  },

  data: function() {
    return {
      uploading: false,
      ossFileUrlSettingInner: {}
    };
  },

  watch: {
    readonly(newVal) {
      if (!newVal) {
        this.$nextTick(function() {
          this.initUpload();
        });
      }
    },
    ossFileUrlSetting(newVal) {
      this.ossFileUrlSettingInner = Object.assign(
        {},
        ossFileUrlSettingDefault,
        this.ossFileUrlSetting
      );
    }
  },

  created() {
    this.ossFileUrlSettingInner = Object.assign(
      {},
      ossFileUrlSettingDefault,
      this.ossFileUrlSetting
    );
  },

  computed: {
    urlList(newVal) {
      var res = _.map(this.value, item => {
        return this.isImage(item.url) ? item.url : "";
      });

      return res ? _.compact(res) : [];
    },
    isExceedFive() {
      return this.value.length < this.max;
    }
  },
  mounted() {
    if (!this.readonly) {
      this.initUpload();
    }
    overMaxTip = _.debounce(() => {
      this.$Message.error("最多上传5个附件");
    }, 100);
  },

  methods: {
    reUploadImg() {
      this.initUpload();
    },
    isImage(url) {
      if (url) {
        url = _.toLower(url.replace(/\?.*/, ""));
      }
      return (
        _.endsWith(url, "png") ||
        _.endsWith(url, "jpg") ||
        _.endsWith(url, "jpeg") ||
        _.endsWith(url, "gif") ||
        _.endsWith(url, "bmp")
      );
    },
    upload(e) {
      if (this.uploading) {
        e.preventDefault();
        return;
      }
      if (this.value.length >= this.max) {
        e.preventDefault();
        overMaxTip();
      }
    },
    showBig(index, flag) {
      this.$refs.imageViewer.viewImage(index, flag);
    },
    showSpecialImg(index) {
      this.$refs.imageViewer.viewSpecImage(index);
    },

    select(item, index) {
      var params = {
        values: this.value,
        itemValue: item,
        index: index
      };
      this.$emit("on-select", params);
    },

    download(item) {
      // console.log(item)
      // const url = `${this.downloadFileUrl}?ossKey=${item.ossKey}&attachName=${item.title}`
      window.open(item.url);
    },

    delFile(item, index, flag) {
      var params = {
        values: this.value,
        itemValue: item,
        index: index
      };
      if (flag) {
        this.$emit("on-del", params);
      } else {
        var value = this.value.filter((it, i) => i !== index);
        var file = _.find(this.uploader.files, function(item2) {
          return item.wid == item2.wid;
        });
        if (file) {
          this.uploader.removeFile(file);
        }

        this.$emit("input", value);
        this.$emit("on-del", item);
        if (item.isDefault) {
          this.value.filter((item1, index) => {
            if (index == 0) {
              item1.isDefault = true;
            }
          });
        }
      }
    },

    fileExtCheck(url, ext) {
      if (url) {
        url = url.replace(/\?.*/, "");
      }
      return _.endsWith(_.toLower(url), ext);
    },

    initUpload() {
      this.uploader = upload.init({
        buttonElement: this.$refs.upload,
        containerElement: this.$refs.uploadcontainer,
        url: this.policyUrl,
        maxFileSize: this.maxFileSize,
        extensions: this.extensions,
        params: this.params || {},
        callbacks: {
          BeforeUpload: () => {
            this.uploading = true;
          },
          FileUploaded: res => {
            this.uploading = false;
            var params = {};
            params[this.ossFileUrlSettingInner.filePathKey] =
              res.filePath + "." + res.ext;
            axios.post(this.ossFileUrl, params).then(res2 => {
              var isDefault = false;
              if (this.value.length == 0) {
                isDefault = true;
              }
              var value = this.value.concat([
                {
                  title: res.fileName,
                  id: res.id,
                  // url: location.protocol + res2[this.ossFileUrlSettingInner.fullPathKey].split(':').slice(1).join(''),
                  url: res2.data.datas,
                  fileName: res.filePath + "." + res.ext,
                  filePath: res.filePath,
                  ossKey: res.filePath + "." + res.ext,
                  ext: res.ext,
                  size: res.size,
                  isDefault: isDefault
                }
              ]);
              this.$emit("input", value);
              this.$emit("file-uploaded", res, res2);
            });
          },
          Error: (a, err) => {
            this.uploading = false;
            if (err.code == -600) {
              this.$Message.warning("上传大小不能超过" + this.maxFileSize);
            } else if (err.code == -601) {
              this.$Message.warning("上传的文件格式不支持！");
            } else if (err.code == -602) {
              this.$Message.warning("文件已上传过，请勿重复上传！");
            }
          }
        }
      });
      //this.uploader.files = []
    }
  }
};

function pickData(data, root) {
  var tempValue = data;
  var rootArray = root.split(">");
  rootArray.forEach(function(item) {
    if (!tempValue[item]) {
      return false;
    }
    tempValue = tempValue[item];
  });
  return tempValue;
}
</script>
<style scoped lang="less" rel="stylesheet/less">
.ivu-upload {
  width: 100%;
  height: 95px;
  line-height: 16px;
  color: #ccc;
  padding: 16px;
  display: inline-block;
  margin-right: 16px;

  .text {
    margin-top: 8px;
    color: #2d8cf0;
    margin-bottom: 8px;
  }
}

.ivu-uploaded {
  display: inline-block;
  width: 170px;
  height: 106px;
  margin-right: 16px;
  border: 1px solid #d7dde4;
  position: relative;
  vertical-align: top;
  border-radius: 4px;
  margin-bottom: 12px;
  img.enlarge-icon {
    top: 50%;
    margin-top: -4px;
    position: absolute;
    cursor: pointer;
  }
  img.image-normal {
    border-radius: 4px;
  }

  .viewer-corner {
    position: absolute;
    width: 0;
    height: 0;
    -webkit-transform: rotate(0);
    -ms-transform: rotate(0);
    transform: rotate(0);
    border-width: 16px;
    border-style: solid;
    right: 0;
    top: 0;
    color: #fff;
    font-size: 12px;
    border-color: #2d8cf0 #2d8cf0 transparent transparent;
    z-index: 999;
    box-shadow: 2px 2px 5px rgba(38, 66, 56, 0.2);
    i {
      position: absolute;
      top: -15px;
      font-size: 17px;
    }
  }

  .opt-panel {
    padding: 24px;
    text-align: center;
    display: none;
    position: absolute;
    width: 100%;
    height: 100%;
    background: rgba(100, 100, 100, 0.8);
    z-index: 20;

    .viewer-selected-btn {
      background-color: rgba(188, 188, 188, 1) !important;
    }

    .viewer-select-btn {
      border-width: 0px;
      position: absolute;
      left: 8px;
      top: 8px;
      width: 46px;
      height: 24px;
      line-height: 23px;
      background: inherit;
      background-color: rgba(45, 140, 240, 1);
      border: none;
      border-radius: 4px;
      -moz-box-shadow: none;
      -webkit-box-shadow: none;
      box-shadow: none;
      font-family: "PingFangSC-Regular", "PingFang SC";
      font-weight: 400;
      font-style: normal;
      font-size: 12px;
      color: #ffffff;
    }

    .viewer-preview-btn {
      position: absolute;
      left: 123px;
      top: 73px;
      width: 24px;
      height: 24px;
      background: #000;
      color: #fff;
      font-size: 18px;
      line-height: 24px;
      border-radius: 4px;
    }

    .viewer {
      height: 50px;
      line-height: 18px;
      color: #ddd;
      text-align: center;
      cursor: pointer;
      width: 60px;
      display: inline-block;
      font-weight: 700;

      &:hover {
        color: #fff;
      }
    }
  }

  &:hover .opt-panel {
    display: block;
  }

  img.image-normal {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }

  .title {
    bottom: -30px;
    width: 100%;
    text-align: center;
    position: absolute;
    overflow: hidden;
    height: 32px;
    overflow: hidden;
  }

  .del {
    position: absolute;
    display: none;
    right: 8px;
    bottom: 0px;
    color: #fff;
    cursor: pointer;
  }

  &:hover .del {
    display: block;
  }
}

.file-img {
  width: 100px !important;
  margin-left: 39px;
  margin-top: 10px;
  height: auto !important;
}

.file-img2 {
  width: 60% !important;
  height: auto !important;
}

.empty {
  color: #bbb;
}

.small-mode-add {
  margin-bottom: 16px;
}

.ivu-icon-md-cloud-upload {
  color: rgb(51, 153, 255);
}
</style>

<style>
.ivu-tooltip-content {
  word-break: break-all;
  word-wrap: break-word;
}
</style>
